ActiveRecord and transactionsin between `before_save` and `save`

Posted by JP on Stack Overflow See other posts from Stack Overflow or by JP
Published on 2010-04-16T09:41:16Z Indexed on 2010/04/16 9:43 UTC
Read the original article Hit count: 161

Filed under:
|
|

I have some logic in before_save whereby (only) when some conditions are met I let the new row be created with special_number equal to the maximum special_number in the database + 1. (If the conditions aren't met then I do something different, so I can't use auto-increments)

My worry is that two threads acting on this database at once might pick the same special_number if the second is executed while the first is saving. Is there way to lock the database between before_save and finishing the save, but only in some cases? I know all saves are sent in transactions, will this do the job for me?

def before_save
  if things_are_just_right
    # -- Issue some kind of lock?
    # -- self.lock? I have no idea
    # Pick new special_number
    new_special = self.class.maximum('special_number') + 1
    write_attribute('special_number',new_special)
  else
    # No need to lock in this case
    write_attribute('special_number',some_other_number)
  end
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about activerecord